﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace Kobets.Automation.Chimera.Common.Commands
{
    public class CommandLineCommand : CommandBase
    {
        private int _curProcId;

        public override void Execute(string content, Guid stepId, CancellationToken token)
        {
            try
            {
                if (File.Exists(@"C:\runtest.bat")) File.Delete(@"C:\runtest.bat");

                // create c:\runtest.bat with the whole execution command
                using (var sw = new StreamWriter(@"C:\runtest.bat"))
                {
                    sw.Write(content);
                    sw.Flush();
                    sw.Close();
                }

                // run it!
                _curProcId = WinApi.RunAs(@"C:\runtest.bat", null, null);

                if (_curProcId == 0)
                {
                    throw new Exception("Command execution failed");
                }

                OnCommandInProgress(new EventArgs<Guid>(stepId));

                // wait until process has finished
                while (!Process.GetProcessById(_curProcId).HasExited)
                {
                    Thread.Sleep(1000);
                    if ( token.IsCancellationRequested ) return;
                }

                OnCommandComplete(new EventArgs<Guid>(stepId));
            }
            catch (Exception ex)
            {
                OnCommandFailed(new EventArgs<KeyValuePair<Guid, Exception>>(new KeyValuePair<Guid, Exception>(stepId, ex)));
            }
        }

        public override void Abort()
        {
            if (_curProcId <= -1) return;

            try
            {
                var proc = Process.GetProcessById(_curProcId);
                if (!proc.HasExited) proc.Kill();
            }
            catch {}
        }
    }
}
